import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:video_player/video_player.dart';
import 'package:grint/bloc/auth_cubit.dart';
import 'package:grint/bloc/comment_cubit.dart';
import 'package:grint/bloc/content_curator_cubit.dart';
import 'package:grint/bloc/follow_cubit.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/entity/comment.dart';
import 'package:grint/entity/content_submission.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/widget/no_data.dart';
import 'package:grint/widget/report_dialog.dart';
import 'package:grint/widget/auth_prompt_dialog.dart';
import 'package:grint/utils/whisper.dart';

class SharePage extends StatefulWidget {
  const SharePage({super.key, required this.shareId});
  final String shareId;

  @override
  State<SharePage> createState() => _SharePageState();
}

class _SharePageState extends State<SharePage> {
  final TextEditingController _commentController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final PageController _pageController = PageController();

  ContentSubmission? currentSubmission;
  bool isLoading = true;
  int currentImageIndex = 0;
  Timer? _autoPlayTimer;

  @override
  void initState() {
    super.initState();
    _loadSubmissionData();
    _loadComments();
  }

  @override
  void dispose() {
    _commentController.dispose();
    _scrollController.dispose();
    _pageController.dispose();
    _autoPlayTimer?.cancel();
    super.dispose();
  }

  void _loadSubmissionData() {
    final contentCubit = context.read<ContentCuratorCubit>();
    final submission =
        contentCubit.state.submissions
            .where((s) => s.submissionId == widget.shareId)
            .firstOrNull;

    setState(() {
      currentSubmission = submission;
      isLoading = false;
    });
  }

  void _loadComments() {
    context.read<CommentCubit>().loadComments(widget.shareId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Positioned.fill(
            child: Image.asset('assets/images/commonBg.png', fit: BoxFit.cover),
          ),

          SafeArea(
            top: false,
            bottom: false,
            child:
                isLoading
                    ? Center(
                      child: CircularProgressIndicator(color: AppColors.blue),
                    )
                    : currentSubmission == null
                    ? _buildErrorView()
                    : SingleChildScrollView(
                      controller: _scrollController,
                      child: Padding(
                        padding: EdgeInsets.only(bottom: 80.h),
                        child: Column(
                          children: [
                            Container(
                              height: 490.h,
                              decoration: BoxDecoration(
                                color: Colors.transparent,
                              ),
                              child: Stack(
                                children: [
                                  Positioned(
                                    top: 0,
                                    left: 0,
                                    right: 0,
                                    bottom: 68.5.h,
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.only(
                                        bottomLeft: Radius.circular(16.r),
                                        bottomRight: Radius.circular(16.r),
                                      ),
                                      child:
                                          currentSubmission != null &&
                                                  currentSubmission!
                                                      .mediaAssets
                                                      .isNotEmpty
                                              ? _buildMediaContent(
                                                currentSubmission!.mediaAssets,
                                              )
                                              : Image.asset(
                                                'assets/images/share1.png',
                                                fit: BoxFit.cover,
                                              ),
                                    ),
                                  ),

                                  Positioned(
                                    top: 56.h,
                                    left: 16.w,
                                    right: 16.w,
                                    child: Row(
                                      children: [
                                        BlackButton(
                                          icon: IconFontIcons.iconArrowLeft,
                                          onTap: () => context.pop(),
                                        ),
                                        const Spacer(),
                                        BlackButton(
                                          icon: IconFontIcons.iconReport2,
                                          onTap: () => _jubaoFenxiangNeirong(),
                                        ),
                                      ],
                                    ),
                                  ),

                                  Positioned(
                                    left: 16.w,
                                    right: 16.w,
                                    bottom: 0,
                                    child: Container(
                                      height: 137.h,
                                      decoration: BoxDecoration(
                                        color: AppColors.white,
                                        borderRadius: BorderRadius.circular(
                                          20.r,
                                        ),
                                      ),
                                      padding: EdgeInsets.only(
                                        left: 20.w,
                                        right: 20.w,
                                        top: 30.h,
                                      ),
                                      child: Column(
                                        children: [
                                          Row(
                                            children: [
                                              ClipRRect(
                                                borderRadius:
                                                    BorderRadius.circular(50.r),
                                                child: CircleAvatar(
                                                  radius: 20.r,
                                                  backgroundColor:
                                                      AppColors.blue,
                                                  child: ClipOval(
                                                    child:
                                                        currentSubmission !=
                                                                null
                                                            ? _buildImageWidget(
                                                              currentSubmission!
                                                                  .authorAvatar,
                                                            )
                                                            : Image.asset(
                                                              'assets/images/avatar-one.png',
                                                              fit: BoxFit.cover,
                                                            ),
                                                  ),
                                                ),
                                              ),
                                              SizedBox(width: 10.w),
                                              MyText(
                                                text:
                                                    currentSubmission
                                                        ?.authorName ??
                                                    'Unknown User',
                                                type: TextType.rubik,
                                                fontSize: 16.sp,
                                                color: AppColors.black,
                                              ),
                                              const Spacer(),
                                              BlocBuilder<
                                                FollowCubit,
                                                FollowState
                                              >(
                                                builder: (
                                                  context,
                                                  followState,
                                                ) {
                                                  final isFollowing =
                                                      currentSubmission != null
                                                          ? followState
                                                              .isFollowing(
                                                                currentSubmission!
                                                                    .authorId,
                                                              )
                                                          : false;

                                                  return GestureDetector(
                                                    onTap: _handleFollowAction,
                                                    child: Container(
                                                      width: 36.w,
                                                      height: 36.w,
                                                      decoration: BoxDecoration(
                                                        color:
                                                            isFollowing
                                                                ? AppColors
                                                                    .textGrey
                                                                : AppColors
                                                                    .blue,
                                                        borderRadius:
                                                            BorderRadius.circular(
                                                              10.r,
                                                            ),
                                                      ),
                                                      child: Icon(
                                                        isFollowing
                                                            ? Icons.check
                                                            : IconFontIcons
                                                                .iconAddLike,
                                                        color: AppColors.white,
                                                        size: 22.sp,
                                                      ),
                                                    ),
                                                  );
                                                },
                                              ),
                                            ],
                                          ),
                                          const Spacer(),
                                          MyText(
                                            text:
                                                currentSubmission
                                                    ?.textDescription ??
                                                'No description available',
                                            maxLines: 2,
                                            overflow: TextOverflow.ellipsis,
                                            type: TextType.miSans,
                                            fontSize: 12.sp,
                                            color: AppColors.black,
                                          ),
                                          const Spacer(),
                                        ],
                                      ),
                                    ),
                                  ),

                                  Positioned(
                                    left: 0,
                                    right: 0,
                                    bottom: 109.h,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceEvenly,
                                      children: [
                                        SizedBox(width: 10.w),
                                        _buildActionButton(
                                          icon: IconFontIcons.iconCollect,
                                          onTap: () => _handleGiftAction(),
                                          isTra: true,
                                        ),
                                        _buildActionButton(
                                          icon: IconFontIcons.iconHome,
                                          onTap: () => _navigateToUserProfile(),
                                          isLarge: true,
                                          iconColor: AppColors.white,
                                          bgColor: AppColors.blue,
                                        ),

                                        BlocBuilder<AuthCubit, AuthState>(
                                          builder: (context, authState) {
                                            final isLiked =
                                                currentSubmission != null &&
                                                        authState.isLoggedIn &&
                                                        authState.currentUser !=
                                                            null
                                                    ? currentSubmission!
                                                        .appreciations
                                                        .any(
                                                          (appreciation) =>
                                                              appreciation
                                                                  .userId ==
                                                              authState
                                                                  .currentUser!
                                                                  .id,
                                                        )
                                                    : false;

                                            return _buildActionButton(
                                              icon:
                                                  isLiked
                                                      ? Icons.favorite
                                                      : Icons.favorite_border,
                                              onTap: () => _handleLikeAction(),
                                              iconColor:
                                                  isLiked
                                                      ? AppColors.red
                                                      : AppColors.black,
                                              bgColor: AppColors.white,
                                            );
                                          },
                                        ),
                                        SizedBox(width: 10.w),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),

                            SizedBox(height: 30.h),

                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: 16.w),
                              child: Align(
                                alignment: Alignment.centerLeft,
                                child: MyText(
                                  text: 'Comments',
                                  type: TextType.rubik,
                                  fontSize: 20.sp,
                                  color: AppColors.black,
                                ),
                              ),
                            ),

                            SizedBox(height: 16.h),

                            _buildCommentsList(),

                            SizedBox(height: 100.h),
                          ],
                        ),
                      ),
                    ),
          ),

          _buildBottomCommentInput(),
        ],
      ),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, size: 64.w, color: AppColors.textGrey),
          SizedBox(height: 16.h),
          MyText(
            text: 'Content not found',
            type: TextType.rubik,
            fontSize: 18.sp,
            color: AppColors.black,
          ),
          SizedBox(height: 8.h),
          MyText(
            text: 'The content you are looking for does not exist',
            type: TextType.miSans,
            fontSize: 14.sp,
            color: AppColors.textGrey,
          ),
        ],
      ),
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required VoidCallback onTap,
    bool isLarge = false,
    bool isTra = false,
    Color? iconColor,
    Color? bgColor,
  }) {
    final size = isLarge ? 68.w : 56.w;
    final iconSize = isLarge ? 30.w : 24.w;

    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: size,
        height: size,
        decoration: BoxDecoration(
          color: isTra ? Colors.transparent : bgColor ?? Colors.white,
          shape: BoxShape.circle,
          boxShadow:
              isTra
                  ? null
                  : [
                    BoxShadow(
                      color: Colors.black.withValues(alpha: 0.1),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
        ),
        child: Icon(
          icon,
          size: iconSize,
          color: isTra ? Colors.transparent : iconColor ?? AppColors.black,
        ),
      ),
    );
  }

  /// 处理送礼操作
  void _handleGiftAction() {
    // 检查登录状态
    if (!_checkLoginStatus(featureName: 'send gifts')) return;

    Whisper.murmur('Gift feature coming soon');
  }

  /// 处理关注操作
  void _handleFollowAction() async {
    // 检查登录状态
    if (!_checkLoginStatus(featureName: 'follow users')) return;

    if (currentSubmission == null) return;

    final followCubit = context.read<FollowCubit>();
    final success = await followCubit.toggleFollow(currentSubmission!.authorId);

    if (success) {
      final isFollowing = followCubit.state.isFollowing(
        currentSubmission!.authorId,
      );
      Whisper.murmur(
        isFollowing ? 'Followed successfully' : 'Unfollowed successfully',
      );
    } else {
      Whisper.hiss('Failed to update follow status');
    }
  }

  /// 导航到用户主页
  void _navigateToUserProfile() {
    if (currentSubmission != null) {
      context.push('/profile/others/${currentSubmission!.authorId}');
    }
  }

  /// 处理点赞操作
  void _handleLikeAction() async {
    // 检查登录状态
    if (!_checkLoginStatus(featureName: 'like content')) return;

    if (currentSubmission == null) return;

    final contentCubit = context.read<ContentCuratorCubit>();
    final authState = context.read<AuthCubit>().state;

    await contentCubit.toggleAppreciationStatus(
      currentSubmission!.submissionId,
      authState.currentUser!,
    );

    // 重新加载数据以更新点赞状态
    _loadSubmissionData();
    // Whisper.murmur('Like updated successfully');
  }

  /// 构建评论列表
  Widget _buildCommentsList() {
    return BlocBuilder<CommentCubit, CommentState>(
      builder: (context, commentState) {
        if (commentState.isLoading) {
          return Center(
            child: Padding(
              padding: EdgeInsets.all(32.h),
              child: CircularProgressIndicator(color: AppColors.blue),
            ),
          );
        }

        if (commentState.comments.isEmpty) {
          return Center(
            child: NoData(width: 120.w, height: 120.w, text: 'No comments yet'),
          );
        }

        return ListView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          itemCount: commentState.comments.length,
          itemBuilder: (context, index) {
            final comment = commentState.comments[index];
            return _buildCommentItem(comment: comment);
          },
        );
      },
    );
  }

  /// 构建单个评论项
  Widget _buildCommentItem({required Comment comment}) {
    // 计算时间差
    final now = DateTime.now();
    final difference = now.difference(comment.createdAt);
    String timeText;

    if (difference.inMinutes < 1) {
      timeText = 'Just now';
    } else if (difference.inHours < 1) {
      timeText = '${difference.inMinutes} minutes ago';
    } else if (difference.inDays < 1) {
      timeText = '${difference.inHours} hours ago';
    } else {
      timeText = '${difference.inDays} days ago';
    }
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      decoration: BoxDecoration(color: Colors.transparent),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户头像
          ClipRRect(
            borderRadius: BorderRadius.circular(20.r),
            child: Image.asset(
              comment.userAvatar,
              width: 40.w,
              height: 40.w,
              fit: BoxFit.cover,
            ),
          ),
          SizedBox(width: 12.w),

          // 评论内容
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户名
                MyText(
                  text: comment.userName,
                  type: TextType.rubik,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  color: AppColors.black,
                ),
                SizedBox(height: 4.h),

                // 评论内容
                MyText(
                  text: comment.content,
                  type: TextType.miSans,
                  fontSize: 13.sp,
                  color: AppColors.black,
                  maxLines: null,
                  overflow: TextOverflow.visible,
                ),
                SizedBox(height: 8.h),

                // 时间
                MyText(
                  text: timeText,
                  type: TextType.miSans,
                  fontSize: 11.sp,
                  color: AppColors.textGrey,
                ),
              ],
            ),
          ),

          // 举报按钮
          GestureDetector(
            onTap: () => _jubaoPinglun(comment),
            child: Icon(
              IconFontIcons.iconReport,
              size: 20.w,
              color: AppColors.black,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomCommentInput() {
    return Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: Container(
        padding: EdgeInsets.fromLTRB(
          16.w,
          12.h,
          16.w,
          MediaQuery.of(context).padding.bottom,
        ),
        decoration: BoxDecoration(color: Colors.transparent),
        child: Row(
          children: [
            Expanded(
              child: Container(
                height: 50.w,
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 6.h),
                decoration: BoxDecoration(
                  color: AppColors.white,
                  borderRadius: BorderRadius.circular(18.r),
                ),
                child: TextField(
                  controller: _commentController,
                  decoration: InputDecoration(
                    hintText: 'Comment',
                    hintStyle: TextStyle(
                      fontSize: 14.sp,
                      color: AppColors.textGrey,
                    ),
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.zero,
                  ),
                  style: TextStyle(fontSize: 14.sp, color: AppColors.black),
                ),
              ),
            ),
            SizedBox(width: 12.w),

            GestureDetector(
              onTap: _sendComment,
              child: Container(
                width: 50.w,
                height: 50.w,
                decoration: BoxDecoration(
                  color: AppColors.white,
                  borderRadius: BorderRadius.circular(18.r),
                ),
                child: Icon(
                  IconFontIcons.iconFasong,
                  size: 26.sp,
                  color: AppColors.black,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 发送评论
  void _sendComment() async {
    if (_commentController.text.trim().isEmpty || currentSubmission == null) {
      return;
    }

    // 检查登录状态
    if (!_checkLoginStatus(featureName: 'comment')) return;

    final authState = context.read<AuthCubit>().state;

    final commentCubit = context.read<CommentCubit>();
    final success = await commentCubit.addComment(
      submissionId: currentSubmission!.submissionId,
      userId: authState.currentUser!.id,
      userName: authState.currentUser!.name,
      userAvatar: authState.currentUser!.avatar,
      content: _commentController.text.trim(),
    );

    if (success) {
      _commentController.clear();
      Whisper.murmur('Comment added successfully');
    } else {
      Whisper.hiss('Failed to add comment');
    }
  }

  /// 构建媒体内容（图片轮播或视频）
  Widget _buildMediaContent(List<MediaAsset> mediaAssets) {
    if (mediaAssets.isEmpty) return Container();

    // 检查是否有视频
    final hasVideo = mediaAssets.any(
      (asset) => asset.mediaType == ContentMediaType.videoClip,
    );

    if (hasVideo) {
      // 如果有视频，只显示第一个视频
      final videoAsset = mediaAssets.firstWhere(
        (asset) => asset.mediaType == ContentMediaType.videoClip,
      );
      return _buildVideoPlayer(videoAsset);
    } else {
      // 如果都是图片，根据数量决定显示方式
      if (mediaAssets.length == 1) {
        return _buildImageWidget(mediaAssets.first.localPath);
      } else {
        return _buildImageCarousel(mediaAssets);
      }
    }
  }

  /// 构建图片轮播
  Widget _buildImageCarousel(List<MediaAsset> imageAssets) {
    // 启动自动播放
    _startAutoPlay(imageAssets.length);

    return Stack(
      children: [
        PageView.builder(
          controller: _pageController,
          itemCount: imageAssets.length,
          itemBuilder: (context, index) {
            return _buildImageWidget(imageAssets[index].localPath);
          },
          onPageChanged: (index) {
            setState(() {
              currentImageIndex = index;
            });
          },
        ),
        // 页面指示器
        if (imageAssets.length > 1)
          Positioned(
            bottom: 20.h,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(
                imageAssets.length,
                (index) => Container(
                  width: 8.w,
                  height: 8.w,
                  margin: EdgeInsets.symmetric(horizontal: 4.w),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color:
                        currentImageIndex == index
                            ? Colors.white
                            : Colors.white.withValues(alpha: 0.5),
                  ),
                ),
              ),
            ),
          ),
        // 图片计数器
        if (imageAssets.length > 1)
          Positioned(
            top: 100.h,
            right: 20.w,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
              decoration: BoxDecoration(
                color: Colors.black.withValues(alpha: 0.6),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: MyText(
                text: '${currentImageIndex + 1}/${imageAssets.length}',
                type: TextType.miSans,
                fontSize: 12.sp,
                color: Colors.white,
              ),
            ),
          ),
      ],
    );
  }

  /// 启动自动播放
  void _startAutoPlay(int itemCount) {
    _autoPlayTimer?.cancel();
    if (itemCount > 1) {
      _autoPlayTimer = Timer.periodic(Duration(seconds: 3), (timer) {
        if (_pageController.hasClients) {
          final nextPage = (currentImageIndex + 1) % itemCount;
          _pageController.animateToPage(
            nextPage,
            duration: Duration(milliseconds: 300),
            curve: Curves.easeInOut,
          );
        }
      });
    }
  }

  /// 构建视频播放器
  Widget _buildVideoPlayer(MediaAsset videoAsset) {
    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: _VideoPlayerWidget(
        videoPath: videoAsset.localPath,
        thumbnailPath: videoAsset.thumbnailPath,
      ),
    );
  }

  /// 构建图片组件
  Widget _buildImageWidget(String imagePath) {
    if (imagePath.startsWith('http')) {
      // 网络图片
      return Image.network(
        imagePath,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Image.asset('assets/images/share1.png', fit: BoxFit.cover);
        },
      );
    } else {
      // 本地图片
      return Image.asset(
        imagePath,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Image.asset('assets/images/share1.png', fit: BoxFit.cover);
        },
      );
    }
  }

  // 检查登录状态的辅助方法
  bool _checkLoginStatus({String? featureName}) {
    final authState = context.read<AuthCubit>().state;
    if (!authState.isLoggedIn || authState.currentUser == null) {
      // 显示登录提示
      if (featureName != null) {
        AuthPromptHelper.showFeatureAuthPrompt(
          featureName,
          context: context,
          onGoToAuth: () {
            context.push('/auth');
          },
        );
      } else {
        AuthPromptHelper.showAuthPrompt(
          context: context,
          onAction: () {
            context.push('/auth');
          },
        );
      }
      return false;
    }
    return true;
  }

  // 举报分享内容
  void _jubaoFenxiangNeirong() {
    FankuiTanchuangBangzhu.xianshi(
      context,
      mubiaoNeirongId: widget.shareId,
      onJubao: (jubaoLeixing, fujiaxinxi) {
        _chuliFenxiangJubao(jubaoLeixing, fujiaxinxi);
      },
    );
  }

  // 处理分享内容举报
  Future<void> _chuliFenxiangJubao(
    JubaoLeixing jubaoLeixing,
    String? fujiaxinxi,
  ) async {
    final contentCubit = context.read<ContentCuratorCubit>();
    final success = await contentCubit.deleteSubmission(widget.shareId);

    if (success) {
      if (mounted) {
        context.pop();
      }
    }
  }

  // 举报评论
  void _jubaoPinglun(Comment comment) {
    FankuiTanchuangBangzhu.xianshi(
      context,
      mubiaoNeirongId: 'comment_${comment.commentId}',
      onJubao: (jubaoLeixing, fujiaxinxi) {
        _chuliPinglunJubao(comment, jubaoLeixing, fujiaxinxi);
      },
    );
  }

  void _chuliPinglunJubao(
    Comment comment,
    JubaoLeixing jubaoLeixing,
    String? fujiaxinxi,
  ) {
    context.read<CommentCubit>().deleteComment(
      comment.commentId,
      comment.shareId,
    );
  }
}

/// 视频播放器组件
class _VideoPlayerWidget extends StatefulWidget {
  final String videoPath;
  final String? thumbnailPath;

  const _VideoPlayerWidget({required this.videoPath, this.thumbnailPath});

  @override
  State<_VideoPlayerWidget> createState() => _VideoPlayerWidgetState();
}

class _VideoPlayerWidgetState extends State<_VideoPlayerWidget> {
  VideoPlayerController? _controller;
  bool showControls = true;
  Timer? _hideControlsTimer;
  bool isInitialized = false;

  @override
  void initState() {
    super.initState();
    _initializeVideoPlayer();
  }

  @override
  void dispose() {
    _hideControlsTimer?.cancel();
    _controller?.dispose();
    super.dispose();
  }

  void _initializeVideoPlayer() async {
    try {
      // 创建视频播放器控制器
      // 智能判断视频类型
      if (_isLocalFile(widget.videoPath)) {
        // 本地文件路径（用户上传的视频或数据初始化复制的视频）
        _controller = VideoPlayerController.file(File(widget.videoPath));
      } else {
        // assets 文件路径（assets 下面的视频）
        _controller = VideoPlayerController.asset(widget.videoPath);
      }

      // 初始化播放器
      await _controller!.initialize();

      // 设置循环播放
      _controller!.setLooping(true);

      // 自动开始播放
      await _controller!.play();

      setState(() {
        isInitialized = true;
      });

      // 3秒后隐藏控制按钮
      _startHideControlsTimer();
    } catch (e) {
      // 视频初始化失败
      setState(() {
        isInitialized = false;
      });
    }
  }

  /// 判断是否为本地文件路径
  bool _isLocalFile(String path) {
    // 本地文件路径的特征：
    // 1. 以 '/' 开头（绝对路径）
    // 2. 包含 'Documents'、'Library'、'tmp' 等系统目录
    // 3. 不以 'assets/' 开头
    return path.startsWith('/') ||
        path.contains('Documents') ||
        path.contains('Library') ||
        path.contains('tmp') ||
        path.contains('Cache') ||
        (!path.startsWith('assets/') && File(path).existsSync());
  }

  void _startHideControlsTimer() {
    _hideControlsTimer?.cancel();
    _hideControlsTimer = Timer(Duration(seconds: 3), () {
      if (mounted) {
        setState(() {
          showControls = false;
        });
      }
    });
  }

  void _togglePlayPause() {
    if (_controller == null || !isInitialized) return;

    setState(() {
      showControls = true;
    });

    if (_controller!.value.isPlaying) {
      _controller!.pause();
    } else {
      _controller!.play();
    }

    _startHideControlsTimer();
  }

  void _showControls() {
    setState(() {
      showControls = true;
    });
    _startHideControlsTimer();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _showControls,
      child: Container(
        width: double.infinity,
        height: double.infinity,
        color: Colors.black,
        child: Stack(
          children: [
            // 视频内容区域
            Positioned.fill(
              child:
                  isInitialized && _controller != null
                      ? VideoPlayer(_controller!)
                      : _buildThumbnail(),
            ),

            // 播放控制按钮
            if (showControls)
              Center(
                child: GestureDetector(
                  onTap: _togglePlayPause,
                  child: Container(
                    width: 80.w,
                    height: 80.w,
                    decoration: BoxDecoration(
                      color: Colors.black.withValues(alpha: 0.6),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      _controller?.value.isPlaying == true
                          ? Icons.pause
                          : Icons.play_arrow,
                      color: Colors.white,
                      size: 40.w,
                    ),
                  ),
                ),
              ),

            // 视频信息
            if (showControls && isInitialized && _controller != null)
              Positioned(
                bottom: 16.h,
                right: 16.w,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: Colors.black.withValues(alpha: 0.7),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: MyText(
                    text: _formatDuration(_controller!.value.duration),
                    type: TextType.miSans,
                    fontSize: 12.sp,
                    color: Colors.white,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, "0");
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "$twoDigitMinutes:$twoDigitSeconds";
  }

  Widget _buildThumbnail() {
    final thumbnailPath = widget.thumbnailPath ?? widget.videoPath;
    return Container(
      width: double.infinity,
      height: double.infinity,
      child:
          thumbnailPath.startsWith('http')
              ? Image.network(
                thumbnailPath,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[800],
                    child: Center(
                      child: Icon(
                        Icons.videocam,
                        size: 60.w,
                        color: Colors.white,
                      ),
                    ),
                  );
                },
              )
              : Image.asset(
                thumbnailPath,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[800],
                    child: Center(
                      child: Icon(
                        Icons.videocam,
                        size: 60.w,
                        color: Colors.white,
                      ),
                    ),
                  );
                },
              ),
    );
  }
}
